package com.pvdnc.tapkit.chat.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.emoji.text.EmojiCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;

import com.pvdnc.nsocket.log.SLog;
import com.pvdnc.nsocket.protocol.PacketCodec;
import com.pvdnc.tapkit.chat.BuildConfig;
import com.pvdnc.tapkit.chat.ChatService;
import com.pvdnc.tapkit.chat.ManagedReference;
import com.pvdnc.tapkit.chat.MessageEntity;
import com.pvdnc.tapkit.chat.R;
import com.pvdnc.tapkit.chat.chat.client.ChatStart;
import com.pvdnc.tapkit.chat.chat.client.MessageReceiver;
import com.pvdnc.tapkit.chat.chat.packet.TextMessage;
import com.pvdnc.tapkit.chat.ui.friend.FunctionAdapter;
import com.pvdnc.tapkit.chat.ui.friend.FunctionEntity;
import com.pvdnc.tapkit.utils.NotificationUtils;

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicBoolean;

public class ChatActivity extends AppCompatActivity {
    private static final SLog LOG=new SLog(ChatActivity.class);

    public static final ManagedReference<ChatStart> mCurrentChat=new ManagedReference<>();

    public static void start(Context context, ChatStart start){
        Intent intent=new Intent(context,ChatActivity.class);
        intent.putExtra(EXTRA_CHAT_START,start);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static final String EXTRA_CHAT_START="chat_start";

    private ChatStart setCurrentChat(Intent intent){
        Serializable serializable=intent.getSerializableExtra(EXTRA_CHAT_START);
        if(!(serializable instanceof ChatStart)) {
            LOG.e("invalid ChatStart extra");
            return null;
        }
        ChatStart start=(ChatStart)serializable;
        mCurrentChat.setRef(start);
        LOG.d("current chat set");
        return start;
    }

    private EditText txtSend;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        //设置标题
        ChatStart chatStart= setCurrentChat(getIntent());
        if(chatStart!=null) {
            setTitle("Chatting on " + chatStart.mToName);
        }

        //发送
        txtSend=findViewById(R.id.txtSend);

        Button cmdSend=findViewById(R.id.cmdSend);
        cmdSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content=txtSend.getText().toString();
                send(content);
                //添加UI
                BubbleEntity bubble=new BubbleEntity(BubbleEntity.DIRECTION_RIGTH);
                bubble.mContent=content;
                mChatAdapter.addData(bubble);

                txtSend.setText(BuildConfig.FLAVOR);
                lvwChat.scrollToPosition(mChatAdapter.getDataSize()-1);//滚动到底部
            }
        });
        initChatView();
        initFunctionView();
    }

    private void send(String content){
        ChatStart chatStart=mCurrentChat.getRef();
        TextMessage textMessage=new TextMessage();
        textMessage.mSrcName=chatStart.mSrcName;
        textMessage.mToName=chatStart.mToName;

        //加密消息内容
        byte[] data= PacketCodec.ENCODING.getBytes(content);
        byte[] encData= ChatService.get().getClient().mKeyManager.encrypt(textMessage.mToName,data);
        textMessage.mContent=Base64.encodeToString(encData,Base64.DEFAULT);

        int level=NotificationUtils.LEVEL_NORMAL;
        if(mImportantOn.get())
            level=NotificationUtils.LEVEL_IMPORTANT;
        textMessage.mLevel= level;
        ChatService.get().send(textMessage,false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LOG.d("onResume");
        mCurrentChat.setReadable(true);
        //注册广播
        mReceiver.register();
    }

    @Override
    protected void onPause() {
        super.onPause();
        LOG.d("onPause");
        mCurrentChat.setReadable(false);
    }

    private MessageReceiver mReceiver=new MessageReceiver() {
        @Override
        public void onReceive(Context context, MessageEntity entity) {
            if(!mCurrentChat.isReadable())
                return;
            ChatStart chatStart=mCurrentChat.getRef();
            if(!chatStart.mToName.equals(entity.mName))
                return;
            BubbleEntity bubble=new BubbleEntity(BubbleEntity.DIRECTION_LEFT);
            bubble.mContent=entity.mContent;
            mChatAdapter.addData(bubble);
            lvwChat.scrollToPosition(mChatAdapter.getDataSize()-1);//滚动到底部
        }
    };

    private ChatAdapter mChatAdapter;
    private RecyclerView lvwChat;
    private void initChatView(){
        lvwChat=findViewById(R.id.lvwChat);
        lvwChat.setLayoutManager(new LinearLayoutManager(this));
        //设置Adapter
        mChatAdapter=new ChatAdapter();
        BubbleEntity bubble=new BubbleEntity(BubbleEntity.DIRECTION_RIGTH);
        bubble.mContent="content right";
        mChatAdapter.addData(bubble);
        //设置绑定
        mChatAdapter.setDataLayoutId(R.layout.item_bubble);
        mChatAdapter.bindRecyclerView(lvwChat);
    }

    private AtomicBoolean mImportantOn=new AtomicBoolean();

    private RecyclerView lvwFunction;
    private FunctionAdapter mFunctionAdapter;
    private void initFunctionView(){
        lvwFunction=findViewById(R.id.lvwFunction);
        LinearLayoutManager honLayoutManager=new LinearLayoutManager(this,
                LinearLayoutManager.HORIZONTAL,false);
        lvwFunction.setLayoutManager(honLayoutManager);
        //设置Adapter
        mFunctionAdapter=new FunctionAdapter();

        //添加Important选项
        FunctionEntity<Switch> importantSwitch=new FunctionEntity<>();
        Switch swImportant=new Switch(this);
        swImportant.setText(R.string.important);
        swImportant.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                LOG.d("switch important status:"+isChecked);
                mImportantOn.set(isChecked);
            }
        });
        importantSwitch.mView=swImportant;
        mFunctionAdapter.addData(importantSwitch);
        //绑定到RecyclerView
        mFunctionAdapter.setDataLayoutId(R.layout.item_chat_function);
        mFunctionAdapter.bindRecyclerView(lvwFunction);
    }
}
